/// author：william on 2021/4/8 10:02
/// email：362661044@qq.com
import 'dart:convert' show json;

import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/enums/base_advanced_filter_type.dart';

class BaseAdvancedFilterModel {
  /// 字段名
  String fieldName;

  /// 名字
  String name;

  /// 注释 input 类型会用到
  String note;

  /// 类型
  BaseAdvancedFilterType inputType;

  /// 是否展开
  bool isExpanded;

  /// 是否隐藏
  bool hidden;

  ///  select 单选多选才会有
  List<BaseKeyValueModel> selectData;

  ///  其他参数
  Map<String, dynamic> otherParam;

  /// 是否必填
  bool required;

  BaseAdvancedFilterModel({
    this.fieldName,
    this.name,
    this.note,
    this.inputType,
    this.otherParam,
    this.selectData,
    this.isExpanded = false,
    this.hidden = false,
    this.required = false,
  });

  factory BaseAdvancedFilterModel.fromJson(Map<String, dynamic> jsonRes) {
    if (jsonRes == null) return null;

    /// 类型
    BaseAdvancedFilterType _inputType;
    if (jsonRes['inputType'] != null && jsonRes['inputType'].toString().isNotEmpty) {
      _inputType = BaseTransformUtil.enumFromString(BaseAdvancedFilterType.values, jsonRes['inputType']);
    }

    /// 选择数据
    final List<BaseKeyValueModel> _selectData = jsonRes['selectData'] is List ? <BaseKeyValueModel>[] : null;
    if (_selectData != null) {
      for (final dynamic item in jsonRes['selectData']) {
        if (item != null) {
          _selectData.add(BaseKeyValueModel.fromJson(asT<Map<dynamic, dynamic>>(item)));
        }
      }
    }

    return BaseAdvancedFilterModel(
      required: asT<bool>(jsonRes['required']),
      fieldName: asT<String>(jsonRes['fieldName']),
      name: asT<String>(jsonRes['name']),
      note: asT<String>(jsonRes['note']),
      inputType: _inputType,
      isExpanded: jsonRes['isExpanded'] ?? false,
      hidden: jsonRes['hidden'] ?? false,
      selectData: _selectData,
    );
  }

  Map<String, dynamic> toJson() => <String, dynamic>{
        'required': required,
        'fieldName': fieldName,
        'name': name,
        'note': note,
        'inputType': BaseTransformUtil.enumToString(inputType),
        'isExpanded': isExpanded,
        'hidden': hidden,
        'selectData': selectData,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}
